//
//  CYLoginViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/5.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYLoginViewController.h"
#import "CYTextField.h"
#import "CYPassWordViewController.h"
#import "CYRegisterViewController.h"
@interface CYLoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) CYTextField *userName;
@property (nonatomic, strong) CYTextField *passWord;
@property (nonatomic, strong) CYButton *loginBtn;
@property (nonatomic, strong) CYButton *forgetPWD_Btn;
@property (nonatomic, strong) CYButton *registerBtn;
@property (nonatomic, strong) CYImageView *IMG;
@property (nonatomic, strong) CYView *line;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation CYLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.line.hidden = NO;
    self.userName.hidden = self.passWord.hidden = self.loginBtn.hidden = self.forgetPWD_Btn.hidden = self.registerBtn.hidden = self.IMG.hidden = NO;
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    // Do any additional setup after loading the view.
}
/*懒加载*/
- (CYTextField *)userName{
    if (!_userName) {
        _userName = [[CYTextField alloc]initWithLeftImage:@"user_login" Placeholder:@"请输入用户名"];
        _userName.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _userName.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        _userName.keyboardType = UIKeyboardTypeASCIICapable;
        _userName.delegate = self;
        [self.view addSubview:_userName];
        
        [_userName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT + AL(PT(150)));
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _userName;
}

- (CYTextField *)passWord{
    if (!_passWord) {
        _passWord = [[CYTextField alloc]initWithLeftImage:@"lock" Placeholder:@"请输入密码"];
        _passWord.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _passWord.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        _passWord.keyboardType = UIKeyboardTypeASCIICapable;
        _passWord.delegate = self;
        _passWord.secureTextEntry = YES;//密码暗文
        [self.view addSubview:_passWord];
        
        [_passWord mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT + AL(PT(150 + 120)));
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _passWord;
}

- (CYButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[CYButton alloc]initWithTitle:@"登录" titleColor:[UIColor lightGrayColor] backgroundColor:ColorHex(0xf4333c) cornerRadius:5];
        [_loginBtn addTarget:self action:@selector(actionForloginBtn:) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.titleLabel.font = [UIFont systemFontOfSize:AL(PT(40))];
        [self.view addSubview:_loginBtn];
        
        [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_passWord.mas_bottom).with.offset( AL(PT(104)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(80))));
        }];
    }
    
    return _loginBtn;
}

- (CYButton *)forgetPWD_Btn{
    if (!_forgetPWD_Btn) {
        _forgetPWD_Btn = [[CYButton alloc]initWithTitle:@"忘记密码" titleColor:ColorHex(0x888888) backgroundColor:[UIColor whiteColor] cornerRadius:0.0];
        [_forgetPWD_Btn addTarget:self action:@selector(actionForForgetPWDBtn) forControlEvents:UIControlEventTouchUpInside];
        [_forgetPWD_Btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _forgetPWD_Btn.titleLabel.font = [UIFont systemFontOfSize:AL(PT(28))];
        [self.view addSubview:_forgetPWD_Btn];
        
        [_forgetPWD_Btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).with.offset(AL(PT(22)));
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.size.mas_equalTo([_forgetPWD_Btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:AL(17)]}]);
        }];
    }
    
    return _forgetPWD_Btn;
}

- (CYButton *)registerBtn{
    
    if (!_registerBtn) {
        _registerBtn = [[CYButton alloc]initWithTitle:@"注册账号" titleColor:ColorHex(0x888888) backgroundColor:[UIColor whiteColor] cornerRadius:0.0];
        [_registerBtn addTarget:self action:@selector(actionForRegisterBtn) forControlEvents:UIControlEventTouchUpInside];
        [_registerBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _registerBtn.titleLabel.font = [UIFont systemFontOfSize:AL(PT(28))];
        [self.view addSubview:_registerBtn];
        
        [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).with.offset(AL(PT(22)));
            make.right.equalTo(self.view.mas_right).with.offset(-AL(PT(60)));
            make.size.mas_equalTo([_forgetPWD_Btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:AL(17)]}]);
        }];
    }
    
    return _registerBtn;
    
}

- (CYImageView *)IMG{
    if (!_IMG) {
        _IMG = [[CYImageView alloc]initWithImage:[UIImage imageNamed:@"background"]];
        [self.view addSubview:_IMG];
        
        [_IMG mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-AL(PT(60)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(AL(2 * PT(_IMG.image.size.width)), AL(2 * PT(_IMG.image.size.height))));
        }];
    }
    return _IMG;
}

- (CYView *)line{
    if (!_line) {
        _line = [[CYView alloc]initWithColor:[UIColor lightGrayColor]];
        [self.view addSubview:_line];
        
        [_line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT , 0, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - 0.5, 0));
        }];
    }
    
    return _line;
}
- (void)actionForRegisterBtn{
    
    CYRegisterViewController *registerVC = [[CYRegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
    
}

- (void)actionForForgetPWDBtn{
    
    CYPassWordViewController *passwordVC = [[CYPassWordViewController alloc]init];
    [self.navigationController pushViewController:passwordVC animated:YES];
    
}

- (void)actionForFreeTrial:(UIBarButtonItem *)sender{
    Class vc = NSClassFromString(@"CYFreeTrialViewController");
    [self.navigationController pushViewController:[vc new] animated:YES];
}

//登录事件
- (void)actionForloginBtn:(CYButton *)sender{
    
    [self endEdit];//结束编辑状态
    NSDictionary *dict = @{@"username":_userName.text,@"password":_passWord.text};
    
    self.task = [CYHttps POST:API_login parameters:dict showHUD:YES progress:nil success:^(id data) {
        DeLog(@"data%@",data);
        if (data) {
            CYUser *user = [CYUser mj_objectWithKeyValues:data];
            [CYUser shareUser].username = user.username;
            [CYUser shareUser].token = user.token;
            Class vc = NSClassFromString(@"CYTabBarController");
            UITabBarController *tabVC = (UITabBarController *)[vc new];
            tabVC.selectedIndex = 0;
            [[UIApplication sharedApplication] keyWindow].rootViewController = tabVC;
        }
    } failure:nil];
    
}

//结束编辑状态，隐藏键盘，view动画复位
- (void)endEdit{
    
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
    
}

//监听键盘的高度,判断是否遮挡登陆按钮
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    CGFloat map = SCREEN_HEIGHT - CGRectGetMaxY(_loginBtn.frame) - height - 10;
    if (map < 0)
        [UIView animateWithDuration:0.3 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map);
        }];
    
}

- (void)back{
    Class vc = NSClassFromString(@"CYTabBarController");
    UITabBarController *tabVC = (UITabBarController *)[vc new];
    tabVC.selectedIndex = 0;
    [[UIApplication sharedApplication] keyWindow].rootViewController = tabVC;
}

#pragma mark uitextfield代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSUInteger another_text_length = ([textField isEqual:_userName])?_passWord.text.length:_userName.text.length;
    UIColor *color = (another_text_length > 0 && (string.length > 0 || textField.text.length > 1))?[UIColor whiteColor]:[UIColor lightGrayColor];
    [_loginBtn setTitleColor:color forState:UIControlStateNormal];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self endEdit];
    return YES;
}


- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:[UIColor whiteColor]];
    self.navigationItem.title = @"登录";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"免费试玩" style:UIBarButtonItemStylePlain target:self action:@selector(actionForFreeTrial:)];
    [self.navigationItem.rightBarButtonItem setTintColor:THEME_COLOR];    //这是导航栏右按钮字体颜色
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
